package com.llcbenwu.controller;

import com.llcbenwu.code.ImageCode;
import com.llcbenwu.generator.ImageCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lilinchun
 * @date 2021/10/26 0026 13:54
 */
@RequestMapping
@RestController
@Api(value = "验证码")
public class VerificationCodeController {


    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";


    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Resource
    private ImageCodeService imageCodeService;

    @GetMapping("/code/image")
    @ApiOperation(value = "验证码图片")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        ImageCode imageCode= ImageCodeUtil.createImageCode(request);
        ImageCode imageCode= imageCodeService.createImageCode(request);
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);
        ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());
    }



}



